<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Django,">










<meta name="description" content="一、URL配置Django 1.11版本 URLConf官方文档 　　URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表。你就是以这种方式告诉Django，对于这个URL调用这段代码，对于那个URL调用那段代码。  1.1基本格式 　12345from django.conf.urls import url#循环urlpatte">
<meta name="keywords" content="Django">
<meta property="og:type" content="article">
<meta property="og:title" content="路由系统">
<meta property="og:url" content="http://yoursite.com/2019/09/21/【Django】02路由系统/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一、URL配置Django 1.11版本 URLConf官方文档 　　URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表。你就是以这种方式告诉Django，对于这个URL调用这段代码，对于那个URL调用那段代码。  1.1基本格式 　12345from django.conf.urls import url#循环urlpatte">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】02路由系统/assets/1566634780699.png">
<meta property="og:updated_time" content="2019-09-21T07:26:02.830Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="路由系统">
<meta name="twitter:description" content="一、URL配置Django 1.11版本 URLConf官方文档 　　URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表。你就是以这种方式告诉Django，对于这个URL调用这段代码，对于那个URL调用那段代码。  1.1基本格式 　12345from django.conf.urls import url#循环urlpatte">
<meta name="twitter:image" content="http://yoursite.com/2019/09/21/【Django】02路由系统/assets/1566634780699.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/21/【Django】02路由系统/">





  <title>路由系统 | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/21/【Django】02路由系统/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">路由系统</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-21T15:24:35+08:00">
                2019-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/Django/" itemprop="url" rel="index">
                    <span itemprop="name">Django</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/21/【Django】02路由系统/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/21/【Django】02路由系统/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一、URL配置"><a href="#一、URL配置" class="headerlink" title="一、URL配置"></a>一、URL配置</h2><p><a href="https://docs.djangoproject.com/en/1.11/topics/http/urls/" target="_blank" rel="noopener">Django 1.11版本 URLConf官方文档</a></p>
<p>　　URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表。你就是以这种方式告诉Django，对于这个URL调用这段代码，对于那个URL调用那段代码。</p>
<p><img src="assets/1566634780699.png" alt="1566634780699"></p>
<h3 id="1-1基本格式"><a href="#1-1基本格式" class="headerlink" title="1.1基本格式 　"></a>1.1基本格式 　</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">from django.conf.urls import url</span><br><span class="line">#循环urlpatterns，找到对应的函数执行,匹配上一个路径就找到对应的函数执行，就不再往下循环了，并给函数传一个参数request，和wsgiref的environ类似，就是请求信息的所有内容</span><br><span class="line">urlpatterns = [</span><br><span class="line">     url(正则表达式, views视图函数，参数，别名),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p> 　　注意：</p>
<p>　　Django 2.0版本中的路由系统已经替换成下面的写法，但是django2.0是向下兼容1.x版本的语法的（<a href="https://docs.djangoproject.com/en/2.0/topics/http/urls/" target="_blank" rel="noopener">官方文档</a>）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">from django.urls import path</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(&apos;articles/2003/&apos;, views.special_case_2003),</span><br><span class="line">    path(&apos;articles/&lt;int:year&gt;/&apos;, views.year_archive),</span><br><span class="line">    path(&apos;articles/&lt;int:year&gt;/&lt;int:month&gt;/&apos;, views.month_archive),</span><br><span class="line">    path(&apos;articles/&lt;int:year&gt;/&lt;int:month&gt;/&lt;slug:slug&gt;/&apos;, views.article_detail),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h3 id="1-2参数说明"><a href="#1-2参数说明" class="headerlink" title="1.2参数说明　"></a>1.2参数说明　</h3><ul>
<li>正则表达式：一个正则表达式字符串</li>
<li>views视图函数：一个可调用对象，通常为一个视图函数或一个指定视图函数路径的字符串</li>
<li>参数：可选的要传递给视图函数的默认参数（字典形式）</li>
<li>别名：一个可选的name参数</li>
</ul>
<h2 id="二-正则表达式详解"><a href="#二-正则表达式详解" class="headerlink" title="二 正则表达式详解"></a>二 正则表达式详解</h2><h3 id="2-1基本配置"><a href="#2-1基本配置" class="headerlink" title="2.1基本配置"></a>2.1基本配置</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">from django.conf.urls import url</span><br><span class="line"></span><br><span class="line">from . import views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(r&apos;^articles/2003/$&apos;, views.special_case_2003), #思考：如果用户想看2004、2005、2006....等，你要写一堆的url吗，是不是在articles后面写一个正则表达式/d&#123;4&#125;/就行啦，网址里面输入127.0.0.1:8000/articles/1999/试一下看看</span><br><span class="line">    url(r&apos;^articles/([0-9]&#123;4&#125;)/$&apos;, views.year_archive), </span><br><span class="line">    url(r&apos;^articles/([0-9]&#123;4&#125;)/([0-9]&#123;2&#125;)/$&apos;, views.month_archive), #思考，如果你想拿到用户输入的什么年份，并通过这个年份去数据库里面匹配对应年份的文章，你怎么办？怎么获取用户输入的年份啊，分组/(\d&#123;4&#125;)/，一个小括号搞定</span><br><span class="line">    url(r&apos;^articles/([0-9]&#123;4&#125;)/([0-9]&#123;2&#125;)/([0-9]+)/$&apos;, views.article_detail),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h3 id="2-2注意事项"><a href="#2-2注意事项" class="headerlink" title="2.2注意事项"></a>2.2注意事项</h3><ol>
<li>urlpatterns中的元素按照书写顺序从上往下逐一匹配正则表达式，一旦匹配成功则不再继续。</li>
<li>若要从URL中捕获一个值，只需要在它周围放置一对圆括号（分组匹配）。</li>
<li>不需要添加一个前导的反斜杠（也就是写在正则最前面的那个/），因为每个URL 都有。例如，应该是^articles 而不是 ^/articles。</li>
<li>每个正则表达式前面的’r’ 是可选的但是建议加上。</li>
<li>^articles&amp;  以什么结尾，以什么开头，严格限制路径</li>
</ol>
<h3 id="2-3补充说明"><a href="#2-3补充说明" class="headerlink" title="2.3补充说明"></a>2.3补充说明</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 是否开启URL访问地址后面不为/跳转至带有/的路径的配置项</span><br><span class="line">APPEND_SLASH=True</span><br></pre></td></tr></table></figure>

<p>　　Django settings.py配置文件中默认没有 APPEND_SLASH 这个参数，但 Django 默认这个参数为 APPEND_SLASH = True。 其作用就是自动在网址结尾加’/‘。其效果就是：我们定义了urls.py：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from django.conf.urls import url</span><br><span class="line">from app01 import views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">        url(r&apos;^blog/$&apos;, views.blog),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>　　访问 <a href="http://www.example.com/blog" target="_blank" rel="noopener">http://www.example.com/blog</a> 时，默认将网址自动转换为 <a href="http://www.example/com/blog/" target="_blank" rel="noopener">http://www.example/com/blog/</a> 。</p>
<p>　　如果在settings.py中设置了 <strong>APPEND_SLASH=False</strong>，此时我们再请求 <a href="http://www.example.com/blog" target="_blank" rel="noopener">http://www.example.com/blog</a> 时就会提示找不到页面。</p>
<h2 id="三-分组命名匹配"><a href="#三-分组命名匹配" class="headerlink" title="三 分组命名匹配"></a>三 分组命名匹配</h2><h3 id="3-1-代码实现"><a href="#3-1-代码实现" class="headerlink" title="3.1 代码实现"></a>3.1 代码实现</h3><p>　　下面是以上URLconf 使用命名组的重写： </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^articles/(?P&lt;year&gt;[0-9]&#123;4&#125;)/$'</span>, views.year_archive),</span><br><span class="line">    <span class="comment">#某年的，(?P&lt;year&gt;[0-9]&#123;4&#125;)这是命名参数</span></span><br><span class="line">    <span class="comment">#函数year_archive(request,year)，形参名称必须是year这个名字。而</span></span><br><span class="line">    <span class="comment">#如果你这个正则后面没有写$符号，即便是输入了月份路径，也会被它拦截下拉，因为它的正则也能匹配上</span></span><br><span class="line">    url(<span class="string">r'^articles/(?P&lt;year&gt;[0-9]&#123;4&#125;)/(?P&lt;month&gt;[0-9]&#123;2&#125;)/(?P&lt;day&gt;[0-9]&#123;2&#125;)/$'</span>, views.article_detail), <span class="comment">#某年某月某日的</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>例如，针对url /articles/2017/12/相当于按以下方式调用视图函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">views.month_archive(request, year=&quot;2017&quot;, month=&quot;12&quot;)，year和month的位置可以换，没所谓了，因为是按照名字来取数据的，还记得关键字参数吗？</span><br></pre></td></tr></table></figure>

<h3 id="3-2URLconf匹配的位置"><a href="#3-2URLconf匹配的位置" class="headerlink" title="3.2URLconf匹配的位置"></a>3.2URLconf匹配的位置</h3><p>　　　URLconf 在请求的URL 上查找，将它当做一个普通的Python 字符串。不包括url的方法（GET和POST）、参数以及域名。</p>
<p>　　　例如，<a href="http://www.example.com/myapp/" target="_blank" rel="noopener">http://www.example.com/myapp/</a> 请求中，URLconf 将查找myapp/。</p>
<p>　　　在<a href="http://www.example.com/myapp/?page=3" target="_blank" rel="noopener">http://www.example.com/myapp/?page=3</a> 请求中，URLconf 仍将查找<code>myapp/</code>。</p>
<h3 id="3-3捕获的参数永远都是字符串"><a href="#3-3捕获的参数永远都是字符串" class="headerlink" title="3.3捕获的参数永远都是字符串"></a>3.3捕获的参数永远都是字符串</h3><p> 　　每个在URLconf中捕获的参数都作为一个普通的Python字符串传递给视图，无论正则表达式使用的是什么匹配方式。例如，下面这行URLconf 中：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">url(<span class="string">r'^articles/(?P&lt;year&gt;[0-9]&#123;4&#125;)/$'</span>, views.year_archive)</span><br><span class="line"><span class="comment">#传递到视图函数views.year_archive() 中的year 参数永远是一个字符串类型。</span></span><br></pre></td></tr></table></figure>

<h3 id="3-4视图函数中指定默认值"><a href="#3-4视图函数中指定默认值" class="headerlink" title="3.4视图函数中指定默认值"></a>3.4视图函数中指定默认值</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># urls.py中</span></span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^blog/$'</span>, views.page),</span><br><span class="line">    url(<span class="string">r'^blog/page(?P&lt;num&gt;[0-9]+)/$'</span>, views.page),</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="comment"># views.py中，可以为num指定默认值</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">page</span><span class="params">(request, num=<span class="string">"1"</span>)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="comment">#两个URL模式指向相同的view - views.page - 但是第一个模式并没有从URL中捕获任何东西</span></span><br><span class="line"><span class="comment">#如果第一个模式匹配上了，page()函数将使用其默认参数num=“1”,如果第二个模式匹配，page()将使用正则表达式捕获到的num值</span></span><br></pre></td></tr></table></figure>

<h3 id="3-5include其他的URLconfs"><a href="#3-5include其他的URLconfs" class="headerlink" title="3.5include其他的URLconfs"></a>3.5include其他的URLconfs</h3><p>1、项目有一个url文档，每一个app有一个对应的urls文档，实现路由分发</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> include, url</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">   url(<span class="string">r'^admin/'</span>, admin.site.urls),</span><br><span class="line">   url(<span class="string">r'^blog/'</span>, include(<span class="string">'blog.urls'</span>)),  <span class="comment"># 可以包含其他的URLconfs文件</span></span><br><span class="line">   url(<span class="string">r'^app01/'</span>,include(<span class="string">'app01.urls'</span>)),  </span><br><span class="line">    <span class="comment">#别忘了要去app01这个应用下创建一个urls.py的文件，</span></span><br><span class="line">    <span class="comment">#凡是以app01开头的路径请求，都让它去找app01下的urls文件中去找对应的视图函数，</span></span><br><span class="line">    <span class="comment">#此时这个文件里面的那个app01路径不能用$结尾，因为如果写了$，就没办法比配上app01/后面的路径了</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>2、app01的urls.py的内容：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="comment">#from django.contrib import admin</span></span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    <span class="comment"># url(r'^admin/', admin.site.urls),</span></span><br><span class="line">    url(<span class="string">r'^articles/2003/'</span>, views.special_case_2003,&#123;<span class="string">'foo'</span>:<span class="string">'xxxxx'</span>&#125;),</span><br><span class="line">    url(<span class="string">r'^articles/(\d&#123;4&#125;)/(\d&#123;2&#125;)/'</span>, views.year_archive),</span><br><span class="line"></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>3、执行过程</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、浏览器发送请求 http://<span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">8000</span>/app01/articles/<span class="number">2003</span>/</span><br><span class="line"><span class="number">2</span>、定位到项目里面的urls.py</span><br><span class="line"><span class="number">3</span>、定位到app01/</span><br><span class="line"><span class="number">4</span>、拿着articles/<span class="number">2003</span>/去app01里面的urls.py文件里面进行匹配</span><br><span class="line"><span class="number">5</span>、执行对应的函数</span><br></pre></td></tr></table></figure>

<h3 id="3-6根路径的写法以及注册app"><a href="#3-6根路径的写法以及注册app" class="headerlink" title="3.6根路径的写法以及注册app"></a>3.6根路径的写法以及注册app</h3><p>1、根路径的匹配写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">url(r&apos;^$&apos;, views.index),#以空开头，还要以空结尾，写在项目的urls.py文件里面就是项目的首页，写在应用文件夹里面的urls.py文件中，那就是app01的首页</span><br></pre></td></tr></table></figure>

<p>2、创建appy应用的的时候记得到配置文件里面进行注册</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = [</span><br><span class="line">    <span class="string">'django.contrib.admin'</span>,</span><br><span class="line">    <span class="string">'django.contrib.auth'</span>,</span><br><span class="line">    <span class="string">'django.contrib.contenttypes'</span>,</span><br><span class="line">    <span class="string">'django.contrib.sessions'</span>,</span><br><span class="line">    <span class="string">'django.contrib.messages'</span>,</span><br><span class="line">    <span class="string">'django.contrib.staticfiles'</span>,</span><br><span class="line">    <span class="string">'rbac.apps.RbacConfig'</span>,</span><br><span class="line">    <span class="string">'app01.apps.App01Config'</span>,</span><br><span class="line">    <span class="comment">#两种写法</span></span><br><span class="line">    <span class="string">'app02.apps.App02Config'</span>,</span><br><span class="line">    <span class="comment">#"app02"</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h3 id="3-7传递额外的参数给视图函数"><a href="#3-7传递额外的参数给视图函数" class="headerlink" title="3.7传递额外的参数给视图函数"></a>3.7传递额外的参数给视图函数</h3><p>　　　URLconfs 具有一个钩子，让你传递一个Python 字典作为额外的参数传递给视图函数。</p>
<p><code>django.conf.urls.url()</code> 函数可以接收一个可选的第三个参数，它是一个字典，表示想要传递给视图函数的额外关键字参数。　</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^blog/(?P&lt;year&gt;[0-9]&#123;4&#125;)/$'</span>, views.year_archive, &#123;<span class="string">'foo'</span>: <span class="string">'bar'</span>&#125;),<span class="comment">#注意，这就像一个命名分组一样，你的函数里面的必须有一个形参，形参必须叫做foo才行。</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h2 id="四-命名URL（别名）和URL的反向解析"><a href="#四-命名URL（别名）和URL的反向解析" class="headerlink" title="四 命名URL（别名）和URL的反向解析"></a>四 命名URL（别名）和URL的反向解析</h2><h3 id="4-1-路由命名"><a href="#4-1-路由命名" class="headerlink" title="4.1 路由命名"></a>4.1 路由命名</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">url(<span class="string">r'^home'</span>, views.home, name=<span class="string">'home'</span>),  </span><br><span class="line"><span class="comment"># 给我的url匹配模式起名（别名）为 home，别名不需要改，路径你就可以随便改了，别的地方使用这个路径，就用别名来搞</span></span><br><span class="line"> url(<span class="string">r'^articles/([0-9]&#123;4&#125;)/$'</span>, views.year_archive, name=<span class="string">'news-year-archive'</span>),  </span><br><span class="line"><span class="comment"># 给我的url匹配模式起名为index</span></span><br></pre></td></tr></table></figure>

<h3 id="4-2反向解析"><a href="#4-2反向解析" class="headerlink" title="4.2反向解析"></a>4.2反向解析</h3><p>1、HTML文件的写法</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;% url <span class="string">'home'</span> %&#125;  <span class="comment">#模板渲染的时候，被django解析成了这个名字对应的那个url，这个过程叫做反向解析</span></span><br><span class="line">&lt;a href="&#123;% url 'news-year-archive' yearvar %&#125;"&gt;&#123;&#123; yearvar &#125;&#125; Archive&lt;/a&gt;</span><br></pre></td></tr></table></figure>

<p> 2、views函数中的写法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> reverse</span><br><span class="line"></span><br><span class="line"><span class="comment">#reverse("index", args=("2018", ))</span></span><br><span class="line"><span class="keyword">return</span> redirect(reverse(<span class="string">'news-year-archive'</span>, args=(year,)))</span><br><span class="line"><span class="comment">#或者直接return redirect('news-year-archive',year)</span></span><br></pre></td></tr></table></figure>

<h2 id="五-命名空间模式"><a href="#五-命名空间模式" class="headerlink" title="五 命名空间模式"></a>五 命名空间模式</h2><p>1、project中的urls.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url, include</span><br><span class="line"> </span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^app01/'</span>, include(<span class="string">'app01.urls'</span>, namespace=<span class="string">'app01'</span>)),</span><br><span class="line">    url(<span class="string">r'^app02/'</span>, include(<span class="string">'app02.urls'</span>, namespace=<span class="string">'app02'</span>)),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>2、app01中的urls.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> views</span><br><span class="line"> </span><br><span class="line">app_name = <span class="string">'app01'</span></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^(?P&lt;pk&gt;\d+)/$'</span>, views.detail, name=<span class="string">'detail'</span>)</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>3、app02中的urls.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> app02 <span class="keyword">import</span> views</span><br><span class="line"> </span><br><span class="line">app_name = <span class="string">'app02'</span></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^(?P&lt;pk&gt;\d+)/$'</span>, views.detail, name=<span class="string">'detail'</span>)</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>4、模板中使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;% url &apos;app01:detail&apos; pk=12 pp=99 %&#125;</span><br></pre></td></tr></table></figure>

<p>5、views中的函数中使用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">v = reverse(&apos;app01:detail&apos;, kwargs=&#123;&apos;pk&apos;:11&#125;)</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/21/【Django】02路由系统/" title="路由系统">http://yoursite.com/2019/09/21/【Django】02路由系统/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/Django/" rel="tag"># Django</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】09From表单和ModelForm组件/" rel="next" title="Form和ModelForm">
                <i class="fa fa-chevron-left"></i> Form和ModelForm
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】03视图函数 - 副本/" rel="prev" title="视图函数">
                视图函数 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、URL配置"><span class="nav-number">1.</span> <span class="nav-text">一、URL配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1基本格式"><span class="nav-number">1.1.</span> <span class="nav-text">1.1基本格式 　</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2参数说明"><span class="nav-number">1.2.</span> <span class="nav-text">1.2参数说明　</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二-正则表达式详解"><span class="nav-number">2.</span> <span class="nav-text">二 正则表达式详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1基本配置"><span class="nav-number">2.1.</span> <span class="nav-text">2.1基本配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2注意事项"><span class="nav-number">2.2.</span> <span class="nav-text">2.2注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3补充说明"><span class="nav-number">2.3.</span> <span class="nav-text">2.3补充说明</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三-分组命名匹配"><span class="nav-number">3.</span> <span class="nav-text">三 分组命名匹配</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-代码实现"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 代码实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2URLconf匹配的位置"><span class="nav-number">3.2.</span> <span class="nav-text">3.2URLconf匹配的位置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3捕获的参数永远都是字符串"><span class="nav-number">3.3.</span> <span class="nav-text">3.3捕获的参数永远都是字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4视图函数中指定默认值"><span class="nav-number">3.4.</span> <span class="nav-text">3.4视图函数中指定默认值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5include其他的URLconfs"><span class="nav-number">3.5.</span> <span class="nav-text">3.5include其他的URLconfs</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6根路径的写法以及注册app"><span class="nav-number">3.6.</span> <span class="nav-text">3.6根路径的写法以及注册app</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7传递额外的参数给视图函数"><span class="nav-number">3.7.</span> <span class="nav-text">3.7传递额外的参数给视图函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四-命名URL（别名）和URL的反向解析"><span class="nav-number">4.</span> <span class="nav-text">四 命名URL（别名）和URL的反向解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-路由命名"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 路由命名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2反向解析"><span class="nav-number">4.2.</span> <span class="nav-text">4.2反向解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五-命名空间模式"><span class="nav-number">5.</span> <span class="nav-text">五 命名空间模式</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
